//
//  GJokeView.m
//  guess
//
//  Created by fank on 15/11/6.
//  Copyright © 2015年 fank. All rights reserved.
//

#import "GJokeView.h"
#import "GHttpEnqine.h"
#import "JokeDataModel.h"
#import "JokeBodyData.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "GJokeTextTVC.h"
#import "Define.h"
#import <MJRefresh/MJRefresh.h>
#import <UIImageView+WebCache.h>
#import "PhotoBroswerVC.h"

@interface GJokeView()<UITableViewDelegate,UITableViewDataSource>
{
    int page;
}
@property CGFloat  heightNum;
@property JokeType joketype;
@property (nonatomic,retain)NSMutableArray * textJokeArr;
@property UITableView * messageTableView;
@property NSMutableArray * heightArr;
@end


@implementation GJokeView
-(instancetype)initWithFrame:(CGRect)frame withJokeTyoe:(JokeType)joketype
{
    self =[super initWithFrame:frame];
    self.messageTableView =[[UITableView alloc]initWithFrame:CGRectMake(0, frame.origin.y, frame.size.width, frame.size.height) style:UITableViewStylePlain];
    [self addSubview:self.messageTableView];
    _joketype =joketype;
    self.messageTableView.delegate = self;
    self.messageTableView.dataSource = self;
    self.messageTableView.delaysContentTouches = NO;
    self.messageTableView.userInteractionEnabled = YES;
    self.messageTableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    self.backgroundColor = UIColorFromRGBValue(0xDBE0E4);
    //集成刷新控件
    [self addHeader];
    [self addFooter];
    self.heightNum =0;
    
    
    return self;
}



- (void)addHeader
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加下拉刷新头部控件
    
    self.messageTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        page = 1;
        [vc getDataWith:page withWay:0];
    }];
    [self.messageTableView.header beginRefreshing];
}

- (void)addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    self.messageTableView.footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        page +=1;
        [vc getDataWith:page withWay:1];
    }];
}





-(void)getDataWith:(int)pageInt withWay:(int)way
{
    NSNumber * pageNum =[NSNumber numberWithInt:pageInt];
    NSLog(@"%@",pageNum);
    [GHttpEnqine getTheJokeWithTheType:_joketype   withThePage:pageNum withComplete:^(id data) {
        [self.messageTableView.header endRefreshing];
        [self.messageTableView.footer endRefreshing];
        NSLog(@"%@",data);
        JokeBodyData * jokeData =[JokeBodyData modelWithDictionary:data error:nil];
        if (way ==1) {
            for (NSDictionary *dict in (NSMutableArray *)jokeData.contentlist) {
                [_textJokeArr addObject:dict];
                
            }
        }else{
            _textJokeArr =[NSMutableArray array];
            for (NSDictionary *dict in (NSMutableArray *)jokeData.contentlist) {
                if ([[dict objectForKey:@"text"]isEqualToString:@"视频加载中..."]||[[dict objectForKey:@"text"]isEqualToString:@""]) {
                    continue;
                }
                [_textJokeArr addObject:dict];
            }
        }
        
        [self.messageTableView reloadData];
    } withfailure:^(id error) {
        [self.messageTableView.header endRefreshing];
        [self.messageTableView.footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:error];
    }];
}




#pragma mark -tableViewDelegate

-(NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return [_textJokeArr count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_joketype ==JokeText) {
        JokeSingleTextDataModel *singleData =[JokeSingleTextDataModel modelWithDictionary:_textJokeArr[indexPath.row] error:nil];
        GJokeTextTVC *cell = [[GJokeTextTVC alloc]initWithTextData:singleData];
        cell.backgroundColor = UIColorFromRGBValue(0xDBE0E4);
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.selfVC = self.GjokeVC;
        cell.tag = indexPath.row;
        [self dealWithCellClick:cell];
        
        return cell;

    }else if(_joketype == JokeImage){
        JokeSingleImageDataModel *singleData =[JokeSingleImageDataModel modelWithDictionary:_textJokeArr[indexPath.row] error:nil];
          GJokeTextTVC *cell = [[GJokeTextTVC alloc]initWithImageData:singleData];
        cell.selfVC =self.selfVC;
        cell.GjokeVC = self.GjokeVC;
        cell.index = indexPath.row ;
        cell.userInteractionEnabled = YES;
        [self configureCell:cell atIndexPath:indexPath];
        cell.backgroundColor = UIColorFromRGBValue(0xDBE0E4);
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [self dealWithCellClick:cell];
        
        __weak typeof(cell) weakCell=cell;
        cell.ClickImageBlock= ^(JokeSingleImageDataModel * singleImageData){
            
            //本地图片展示
//            [self localImageShow:index];
            
            //展示网络图片
            [self networkImageShow:indexPath.row withSingleImageData:singleImageData withTheCell:weakCell];
        };

        
        
        return cell;
    }else{
        JokeSingleTextDataModel *singleData =[JokeSingleTextDataModel modelWithDictionary:_textJokeArr[indexPath.row] error:nil];
        GJokeTextTVC *cell = [[GJokeTextTVC alloc]initWithTextData:singleData];
        [self dealWithCellClick:cell];
        return cell;
    }
    
   }


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_joketype ==JokeText) {
    JokeSingleTextDataModel *singleData =[JokeSingleTextDataModel modelWithDictionary:_textJokeArr[indexPath.row] error:nil];
    NSString * labelStr = singleData.text;
    CGSize labelSize = {0, 0};
    labelSize = [labelStr sizeWithFont:[UIFont systemFontOfSize:17]
                     constrainedToSize:CGSizeMake(kscreenWith - 20, 5000)
                         lineBreakMode:NSLineBreakByWordWrapping];
    return  90 + labelSize.height;
    }else if(_joketype ==JokeImage){
        JokeSingleImageDataModel *singleData =[JokeSingleImageDataModel modelWithDictionary:_textJokeArr[indexPath.row] error:nil];

         UIImage *img = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey: singleData.img ];
        if (!img) {
             img = [UIImage imageNamed:@"placehold"];
        }
         CGSize size = [GJokeTextTVC heightWithImage:img];
        CGFloat height = size.height/size.width*(kscreenWith-20);

        return height+90;
    }else{
        return 10;
    }
}

- (void)configureCell:(GJokeTextTVC *)cell atIndexPath:(NSIndexPath *)indexPath
{
    // 正常的设置文字和其他内容
    JokeSingleImageDataModel *singleData =[JokeSingleImageDataModel modelWithDictionary:_textJokeArr[indexPath.row] error:nil];
    // 开始加载图片
    NSString *imgURL = singleData.img;    // 图片 url
    UIImage *cachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgURL];
    
    // 没有已经下载好的图片
    if ( !cachedImage ) {
        // 要是当前 table view 没有在被拖动或者自由滑行
        if ( !self.messageTableView.dragging && !self.messageTableView.decelerating ) {
            // 下载当前 cell 中的图片
            [self downloadImage:imgURL forIndexPath:indexPath];
        }
        // cell 中图片先用缓存的占位图代替
        [cell setSpitslotImage:[UIImage imageNamed:@"placehold"]];
    } else {
        // 找到了缓存的图片，直接插缓存的图片
        [cell setSpitslotImage:cachedImage];
    }
}


- (void)downloadImage:(NSString *)imageURL forIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) target = self;
    // 利用 SDWebImage 框架提供的功能下载图片
    [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString: imageURL] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        // 保存图片
        [[SDImageCache sharedImageCache] storeImage:image forKey:imageURL toDisk:YES]; // 别忘了保存到磁盘上
        
        // 延迟在主线程更新 cell 的高度
        [target performSelectorOnMainThread:@selector(reloadCellAtIndexPath:)       // 至于这步的原因是为了防止刷的太快了崩溃
                                 withObject:indexPath waitUntilDone:NO];            // 这步会把 selector 的调用放到主线程的 run loop 里排队
    }];
   }

- (void)loadImageForOnScreenRows
{
    NSArray *visiableIndexPathes = [self.messageTableView indexPathsForVisibleRows];
    
    for(NSInteger i = 0; i < [visiableIndexPathes count]; i++)
    {
        JokeSingleImageDataModel *singleData =[JokeSingleImageDataModel modelWithDictionary:_textJokeArr[i] error:nil];
        NSString *imgURL = singleData.img;
        [self downloadImage:imgURL forIndexPath:visiableIndexPathes[i]];
    }
}

- (void)reloadCellAtIndexPath:(NSIndexPath *)indexPath
{
    [self.messageTableView reloadData];
}

#pragma mark - Scroll view delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    // table view 停止拖动了
    if (!decelerate&&_joketype==JokeImage) {
        [self loadImageForOnScreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // table view 停止滚动了
    if (_joketype == JokeImage) {
         [self loadImageForOnScreenRows];
    }
   
}




#pragma mark - show image delegate
/*
 *  展示网络图片
 */
-(void)networkImageShow:(NSUInteger)index withSingleImageData:(JokeSingleImageDataModel *)jokeSingleImageDataModel withTheCell:(GJokeTextTVC *)cell{
    
    [PhotoBroswerVC show:self.selfVC type:PhotoBroswerVCTypeZoom index:index photoModelBlock:^NSArray *{
        
        NSMutableArray *modelsM = [NSMutableArray arrayWithCapacity:_textJokeArr.count];
        for (NSUInteger i = 0; i< _textJokeArr.count; i++) {
            JokeSingleImageDataModel *singleData =[JokeSingleImageDataModel modelWithDictionary:_textJokeArr[i] error:nil];
            PhotoModel *pbModel=[[PhotoModel alloc] init];
            pbModel.mid = i + 1;

            pbModel.title = [NSString stringWithFormat:@"%@            %@",@(i+1),[singleData.ct substringToIndex:19]];
            pbModel.desc = [NSString stringWithFormat:@"%@",singleData.title];
            pbModel.image_HD_U = singleData.img;
            
            //源frame
            UIImageView *imageV =(UIImageView *) cell.imageImg;
            pbModel.sourceImageView = imageV;
            
            [modelsM addObject:pbModel];
        }
        
        return modelsM;
    }];
}



//处理cell 不能点击的问题
-(void)dealWithCellClick:(UITableViewCell *)cell
{
    for (id obj in cell.subviews)
    {
        if ([NSStringFromClass([obj class])isEqualToString:@"UITableViewCellScrollView"])
        {
            UIScrollView *scroll = (UIScrollView *) obj;
            scroll.delaysContentTouches =NO;
            break;
        }
    }
}


//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}

@end
